To change the attributes of multiple elements based on user input or other dynamic conditions. Use to update attributes for multiple elements.setAttribute
Let say you want to show image by selecting from dropdown.
<!-- Dropdown -->
<select id="imageSelector">
<option value="image1.jpg" data-alt="Image 1 Description">Image 1</option>
<option value="image2.jpg" data-alt="Image 2 Description">Image 2</option>
<option value="image3.jpg" data-alt="Image 3 Description">Image 3</option>
</select>
<!-- Show image here -->
<div id="gallery">
<img id="mainImage" src="default.jpg" alt="Default Image">
</div>Javascript:
<script>
document.getElementById('imageSelector').addEventListener('change', function() {
// get selected item's url and alt
const selectedOption = this.options[this.selectedIndex];
const imageUrl = selectedOption.value;
const imageAlt = selectedOption.getAttribute('data-alt');
const mainImage = document.getElementById('mainImage');
mainImage.setAttribute('src', imageUrl); // set url of image
mainImage.setAttribute('alt', imageAlt); // set alt attribute of image
});
</script>You Might Also Like
Remove Multiple DOM Elements
Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...
Efficiently Append Multiple Elements
Appending multiple elements to the DOM can be inefficient if done individually. Use a document frag...